package com.cai.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cai.demo.dao.RolePermissionMapper;
import com.cai.demo.dao.UserMapper;
import com.cai.demo.entity.RolePermission;
import com.cai.demo.entity.User;
import com.cai.demo.entity.UserRole;
import com.cai.demo.service.*;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Title: UserServiceImpl
 * @Author RuoLi
 * @Package com.cai.demo.service.impl
 * @Date 2023/12/14 20:56
 * @description:
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private RolePermissionService rolePermissionService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private UserService userService;

    @Override
    public Set<Integer> getPermission(String username) {
        QueryWrapper<User> userWrapper = new QueryWrapper<>();
        userWrapper.eq("username", username);
        Integer userId = userService.getOne(userWrapper).getId();
        //用户id查询用户的角色
        QueryWrapper<UserRole> userRoleWrapper = new QueryWrapper<>();
        userRoleWrapper.eq("user_id", userId);
        Integer roleId = userRoleService.getOne(userRoleWrapper).getRoleId();
        //角色id查询权限
        QueryWrapper<RolePermission> rolePermissionWrapper = new QueryWrapper<>();
        rolePermissionWrapper.eq("role_id", roleId);
        List<RolePermission> rolePermissions = rolePermissionService.list(rolePermissionWrapper);
        //封装角色权限
        Set<Integer> permissionIds = new HashSet<>();
        for (RolePermission rolePermission : rolePermissions) {
            permissionIds.add(rolePermission.getPermissionId());
        }
        return permissionIds;
    }
}
